<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 搜索和添加 -->

      <el-row :gutter="10">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserlist">
            <el-button slot="append" icon="el-icon-search" @click="getUserlist"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>

        <!-- <el-table-column
        prop="emai"
        label="邮箱"
       >
        </el-table-column>-->

        <el-table-column prop="mobile" label="电话"></el-table-column>

        <el-table-column label="角色" prop='managername'>
          <!-- <template slot-scope="scope">
            <el-tag v-if="scope.row.Uright==='0'">普通用户</el-tag>
            <el-tag v-else-if="scope.row.Uright==='5'">超级管理员</el-tag>
          </template> -->
        </el-table-column>

        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch  active-value='1' inactive-value='0' v-model="scope.row.Ustate" @change="userStateChanged(scope.row)"></el-switch>
          </template>
              
           
         
        </el-table-column>

        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 分配 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 6, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="30%" @close="addDialogClosed">
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="ruleFormRef"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"  ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input   type="password" v-model="addForm.password"    ></el-input>
        </el-form-item>
        <!-- <el-form-item label=邮箱 prop="email">
    <el-input v-model="addForm.email"></el-input>
        </el-form-item>-->
          <el-form-item label="确认密码" prop="passwordSure">
          <el-input
           
            v-model="addForm
          .passwordSure"
            type="password"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 操作按钮 -->
    <!-- 修改 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <!-- <el-form-item label="邮箱" prop="email">
    <el-input v-model="editForm.email" ></el-input>
        </el-form-item>-->
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!--分配角色对话框  -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" @close="setRoleDialogClosed">
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <!-- <p v-if="userInfo.Uright==='5'">当前的角色：超级管理员</p>
        <p v-else-if="userInfo.Uright==='0'">当前的角色：普通用户</p> -->
        <p>当前的角色: {{userInfo.managername}}</p>
                 
        <p>
          分配新角色
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
 <script>
export default {
  data() {
    //验证邮箱
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法邮箱"));
    };

    //验证手机
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]18[0-9]14[57])[0-9]{8}$/;

      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法手机号"));
    };
    //验证密码
        var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.addForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    //验证用户名
    var checkName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (value.length < 3 || value.length > 20) {
        callback(new Error("请输入长度在 3 到 20个字符!"));
      } else {
        this.checkNameOver(callback);
      }
    };

    return {
      queryInfo: {
        query: "",
        //当前页数
        pagenum: 0,
        //显示多少条数据
        pagesize: 10,
      },
      userList: [],
      total: 0,
      addDialogVisible: false,
      //添加用户
      addForm: { username: "123", password: "123456", passwordSure: "123456" },
       addFormRules: {
        username: [
          //   { required: true, message: "请输入用户名", trigger: "blur" },
          //   { min: 3, max: 20, message: "长度在 3 到 20个字符", trigger: "blur" },
          { validator: checkName, trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 20, message: "长度在 6 到 20个字符", trigger: "blur" },
        ],
        passwordSure: [{ validator: validatePass, trigger: "blur" }],
      },
      editDialogVisible: false,

      editForm: {},
      //修改表单验证规则
      editFormRules: {
        email: [
          {
            required: true,
            message: "请输入用户邮箱",
            trigger: "blur",
          },
          { validator: checkEmail, trigger: blur },
        ],
        mobile: [
          { required: true, message: "请输入用户手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: blur },
        ],
      },
      //控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      //需要被分配角色的用户信息
      userInfo: {},
      //所有角色的数据列表
      rolesList: [],
      selectedRoleId: '',
    };
  },
  created() {
    this.getUserlist();
  },
  methods: {
    async getUserlist() {
        console.log(this.queryInfo.query,'query');
       
            // const {data} =   await  this.$http.get('/getUser-token') 测试接口
       const {data} =   await  this.$http.get('/users',
       {params:{query:this.queryInfo }})
       console.log(data);
     
      //  if(res.meta.status!==200) return this.$message.error('获取用户列表失败')
      // this.userList=res.data.users
      // this.total=res.data.total
      // const res = await this.$http.get("/users");

      this.userList = data.data;
      this.total=data.total
 
    },
  
                handleSizeChange(newsize){
    console.log(newsize)
    this.queryInfo.pagesize=newsize
    this.getUserlist()
                },
                //监听页码值变化
                handleCurrentChange(newpage){
                  console.log(newpage)
                  this.queryInfo.pagenum=newpage
                  this.getUserlist()
                },

    //             //监听 开关状态变化
    async userStateChanged(userinfo) {
      const res = await this.$http.put(
        `users/${userinfo.id}/Ustate/${userinfo.Ustate}`
      );
    console.log(res);
      console.log(userinfo);
  
      // if (res.meta.status != 200) {
      //   userinfo.mg_state = !userinfo.mg_state;
      //   return this.$message.error("更新状态失败");
      // }
      this.$message.success("更新状态成功");
    },
    // //重置表单
     addDialogClosed(){
    this.$refs.ruleFormRef.resetFields()
     },

    //点击按钮，添加新用户
    addUser() {
      this.$refs.ruleFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data } = await this.$http.post("/users", this.addForm);
        console.log(data);
        //  if(res.meta.status!==201){
        //    this.$message.error('添加用户失败！')
        //  }
        console.log(this.addForm);
        this.$message.success("添加成功！");
        //隐藏对话框
        this.addDialogVisible = false;
        //重新获用户列表
        this.getUserlist();
      });
    },

    //修改用户部分
    async showEditDialog(id) {
      console.log(id);
      const { data } = await this.$http.get("user/" + id);

      // if(res.meta.status!==200) {
      //   return this.$message.error('查询用户失败')
      // }
     
      this.editForm = data.data[0];

      this.editDialogVisible = true;
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },

    //修改用户并且提交
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const res = await this.$http.put("users/" + this.editForm.id, {
          mobile: this.editForm.mobile,
        });
        // if (res.meta.status !== 200) {
        //   return this.$message.error("修改失败");
        // }
        console.log(res);
        //关闭对话框 刷新数据 提示成功
        this.editDialogVisible = false;
        this.getUserlist();
        this.$message.success("修改成功");
      });
    },

    //  //删除用户
    async removeUserById(id) {
      //弹框询问是否删除
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      //如果用户点击确定，返回字符串confirm
      //取消删除。返回字符串cancel
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      //  const {data:res}= await this.$http.delete('users/'+id)
      const { data } = await this.$http.delete("/users/" + id);
      console.log(data);
      //  if(res.meta.status!==200){
      //    return this.$message.error('删除失败')
      //  }
      this.$message.success("删除成功");
      this.getUserlist();
    },
    //展示分配角色的
    async setRole(userinfo) {
     
      console.log(userinfo);
      this.userInfo = userinfo;
      //展示对话框前，获取所有角色的列表
      const res= await this.$http.get("roles");
      //  console.log(res)
      // if (res.meta.status !== 200) {
      //   return this.$message.error("获取角色数据失败");
      // }
      // this.$message.success('获取角色数据成功')
  this.rolesList = res.data;
  this.selectedRoleId=this.userInfo.Uright
      this.setRoleDialogVisible = true;
    },
    //点击按钮，确定分配角色
    async saveRoleInfo() {
      if (typeof(this.selectedRoleId)!=='string') {
        return this.$message.error("请选择角色");
      }
// console.log(typeof(this.selectedRoleId) ,11111111);
      const res = await this.$http.put(`users/${this.userInfo.id}/role`, {
        managername: this.selectedRoleId,
      });
      // console.log(res);
      // console.log(this.userInfo.id);
      // if (res.meta.status !== 200) {
      //   return this.$message.error("更新角色成功");
      // }
      this.$message.success("更新角色成功");
      this.getUserlist();
      this.setRoleDialogVisible = false;
    },
    setRoleDialogClosed() {
      this.selectedRoleId = "";
      this.userInfo = {};
    },
        //验证名字是否被注册过
    async checkNameOver(callback) {
      if (this.addForm.username.length < 3) return;

      const res = await this.$http.get(
        "/checkname/" + this.addForm.username
      );
      if (res.data.state === 200) {
        callback();
      } else {
        callback(new Error("用户名被注册过了"));
      }
    },
  },
};
</script>
    <style lang="less" scoped>
</style>